
function loadToMainContent(url) {
	$.ajax({
		url: url,
		success: function(data) {
			resetErrorMessage();
			$("#maincontent").html(data); // load the content of the response to the div
			if(url.indexOf("newTask.jsp") != -1 || url.indexOf("newTeam.jsp") != -1 ||
					url.indexOf("task.jsp") != -1 || url.indexOf("team.jsp") != -1 ||
					url.indexOf("searchPost.jsp") != -1 || url.indexOf("myPosts.jsp") != -1) {
				function loadGoogleMaps() {
					var script_tag = document.createElement("script");
					script_tag.setAttribute("type", "text/javascript");
					script_tag.setAttribute("src", "https://maps.googleapis.com/maps/api/js?key=AIzaSyD_XmrH2KJHbxXlmDwAhVd8KSdFMZ0NGOk&sensor=false&callback=gMapsCallback");
					(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
				}
				$(window).bind('gMapsLoaded', initializeMap);
				loadGoogleMaps();
			}
		}, // success function
		error: function(xhr, ajaxOptions, thrownError) {
			var err = xhr.responseText;
			if(err.indexOf("<?xml version=\"1.0\" encoding=\"windows-1255\" ?>") != -1) {
				err = err.split("<?xml version=\"1.0\" encoding=\"windows-1255\" ?>");
				err = err[1].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
			}
			errorMessage(err, false);
		}
	}); // ajax request
}

function loadDefaults(username) {
	loadToMainContent("searchPost.jsp");
	updateUsernameForMaps(username);
}

function addSkillBox(selected) {
	var newBox = document.createElement("p");
	newBox.setAttribute("id", "newSkill" + selected.selectedIndex);
	newBox.innerHTML = selected.options[selected.selectedIndex].text + "<img src=\"images/delete.png\" " +
			"onclick=\"removeSelectedSkill(" + selected.selectedIndex + ")\"/>" +
			"<input type=\"text\" hidden value=\"" + selected.options[selected.selectedIndex].value +
			"\" name=\"newSkillId" + selected.selectedIndex + "\" />";
			document.getElementById("skillsListDiv").appendChild(newBox);
	selected.options[selected.selectedIndex].disabled = true;
	selected.selectedIndex = 0;
}

function removeSelectedSkill(indexToReturn) {
	var selected = document.getElementById("skill1");
	selected.options[indexToReturn].disabled = false;
	var divSkills = document.getElementById("skillsListDiv");
	divSkills.removeChild(document.getElementById("newSkill" + indexToReturn));
}

function validateUserInputForNewPost() {
	// map validation
	if(!googleMapScripts_isUserMarkerValid) {
		errorMessage("Please select position for the task", false);
		return false;
	}
	document.getElementById("latPos").value=googleMapScripts_userMarker.getPosition().lat();
	document.getElementById("lngPos").value=googleMapScripts_userMarker.getPosition().lng();
	
	var valCap = parseInt(document.getElementById("capacity").value);
	if(valCap && valCap < 0) {
		errorMessage("Number of people to evacuate must be a positive number", false);
		return false;
	}
	return true;
}

function validateUserInputForSearch() {
	// map validation
	if(!googleMapScripts_isUserMarkerValid) {
		errorMessage("Please select position for the center of the search", false);
		return;
	}
	document.getElementById("latPos").value=googleMapScripts_userMarker.getPosition().lat();
	document.getElementById("lngPos").value=googleMapScripts_userMarker.getPosition().lng();
	// check thet the distance is a positive integer
	var radius = document.getElementById("radius").value;
	if(isNaN(radius) || radius < 0) {
		alert("The distance should be a positive number");
	}
	radius = $("#radius").prop("value");
	latPos = $("#latPos").prop("value");
	lngPos = $("#lngPos").prop("value");
	bringTasks = document.getElementById("bringTasks").checked;
	bringTeams = document.getElementById("bringTeams").checked;
	bringMatches = document.getElementById("bringMatches").checked;
	// run the search.
	searchPosts(radius, latPos, lngPos, bringTasks, bringTeams, bringMatches);
	sendSearchRequest(radius, latPos, lngPos);
}

function sendSearchRequest(radius, latPos, lngPos) {
	$.ajax({
		url: "SearchResults",
		data: {"radius": radius, "latPos": latPos, "lngPos": lngPos},
		type: "post",
		success: function(data) {
			resetErrorMessage();
			$("#resultDiv").html(data);
			displaySearchTypes();
		},
		error:function(xhr, ajaxOptions, thrownError) {
			errorMessage(xhr.responseText, false);
		}
	});
}

function displaySearchTypes() {
	displayTasks = document.getElementById("bringTasks").checked;
	displayTeams = document.getElementById("bringTeams").checked;
	if(!document.getElementById("taskResults") || !document.getElementById("taskResults").hidden) { return; }
	if(displayTasks == true) {
		document.getElementById("taskResults").hidden = false;
	} else {
		document.getElementById("taskResults").hidden = true;
	}
	if(displayTeams == true) {
		document.getElementById("teamResults").hidden = false;
	} else {
		document.getElementById("teamResults").hidden = true;
	}
}

function setKMLVisibleForSearch(){
	showTasks = document.getElementById("bringTasks").checked;
	showTeams = document.getElementById("bringTeams").checked;
	showMatches = document.getElementById("bringMatches").checked;
	setKMLVisible(showTasks,showTeams,showMatches);
}

function addPost(url, onsuccessUrl) {
	if(!validateUserInputForNewPost()) { return; }
	$.ajax({
		url: url,
		data: $('#addPost').serialize(),
		type: "post",
		success: function(data) {
			resetErrorMessage();
			loadToMainContent(onsuccessUrl + "?postId=" + data);
		},
		error:function(xhr, ajaxOptions, thrownError) {
			errorMessage(xhr.responseText, false);
		}
	});
}

function updatePost(url, formName) {
	$.ajax({
		url: url,
		data: $('#' + formName).serialize(),
		type: "post",
		success: function(data) {
			errorMessage(data, true);
		},
		error:function(xhr, ajaxOptions, thrownError) {
			errorMessage(xhr.responseText, false);
		}
	});
}

function adminDel(row, id, command) {
	$.ajax({
		url:"admin/AdminTools",
		data:{"command": command, "id": id},
		type:"post",
		success:function() {
			resetErrorMessage();
			document.getElementById("adminTable").deleteRow(row);
		},
		error:function(xhr, ajaxOptions, thrownError) {
			errorMessage(xhr.responseText, false);
		}
	});
}

function updateProfile() {
	$.ajax({
		url: "UpdateProfile",
		data: $("#updateForm").serialize(),
		type: "post",
		success:function() {
		},
		error:function(xhr, ajaxOptions, thrownError) {
			errorMessage(xhr.responseText, false);
		}
	});
	return false;
}

function errorMessage(msg, noAlert) {
	document.getElementById("errorMessage").innerHTML = msg;
	if(!noAlert) {
		alert(msg);
	}
}

function resetErrorMessage() {
	document.getElementById("errorMessage").innerHTML = "";
}
